package login;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet("/login")
public class loginServlet extends HttpServlet {

    public void setFormattedLoginTime(HttpSession session) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String formattedDate = formatter.format(new Date());
        session.setAttribute("loginTime", formattedDate);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        // 简单的登录逻辑，假设用户名是"张三"且密码是"123"
        if (!"张三".equals(username) || !"123".equals(password)) {
            resp.setContentType("text/html; charset=utf-8");
            resp.getWriter().write("您的账号信息或密码有误!");
            return;
        }

        // 登录成功，为用户创建一个会话
        HttpSession session = req.getSession(true);
        session.setAttribute("username", username);
        setFormattedLoginTime(session);

        // 登录成功之后跳转到其他页面
        resp.sendRedirect("index");
    }
}
